//
//  NetworkTools.swift
//  AFNTools
//
//  Created by SteveLi on 2017/9/30.
//  Copyright © 2017年 李军桦. All rights reserved.
//

import UIKit
import AFNetworking

//请求方法枚举
enum HMRequestMethod:String{
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    //let  appKey = "2107945159"
    //let  appSecret = "1dfb496f019993833c3d382ad0846bd9"
    let  appKey = "420111289"
    let  appSecret = "25d2f5e8a0a6302fbc9e236f23d1ac7c"
    let  redirectUrl = "http://www.baidu.com"
    
    //类似于 OC 的typeDefine
    typealias HMRequestCallBack = (_ result: Any?,_ error: Error?)->()
    
    /// 单例
    static let sharedTools:NetworkTools = {
        let tools = NetworkTools(baseURL: nil)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    //返回 token 字典
    var tokenDict:[String:Any]?{
        //判断 token 是否有效
        if let token = UserAccountViewModel.sharedUserAccount.accessToken {
                    return ["access_token":token]
        }
        return nil
    }
}

//MARK: -微博数据相关方法
extension NetworkTools {
    /// /// 加载微博数据
    ///  since_id :若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    ///  max_id :若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    /// - parameter finished: 完成回调
    func loadStatus( since_id:Int, max_id: Int, finished:@escaping HMRequestCallBack) {

        //1.获取token字典
        guard var params = tokenDict else {
            //如果字典为 nil ,通知调用方 token无效
            finished(nil, NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message":"token 为 空"]))
            return
        }
        //判断是否下拉
        if since_id > 0 {
            params["since_id"] = since_id
        } else if max_id > 0 { //上拉参数
            params["max_id"] = max_id - 1
        }
        
        //2.准备网络参数
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //3.发起网络请求
        request(method: .GET, urlString: urlString, parameters: params, finished: finished)
    }
}


//MARK: - 用户相关方法
extension NetworkTools {
    
    func loadUserInfo(uid:String,finished:@escaping HMRequestCallBack){
        //1.获取token字典
        guard var params = tokenDict else {
            //如果字典为 nil ,通知调用方 token无效
            finished(nil, NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message":"token 为 空"]))
                return
        }
        //2.处理网络参数
        
        let urlString = "https://api.weibo.com/2/users/show.json"
         params["uid"] = uid
        
        //["uid":uid,"access_token":accessToken]
        request(method: .GET, urlString: urlString, parameters: params, finished: finished)
        
    }
}



//MARK: -Auth
extension NetworkTools{
    /// Oauth 授权URL
    /// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthURL:NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        print(urlString)
        return NSURL(string: urlString)!
    }
    /// 加载 AccessToken
    func loadAccessToken(code: String,finished:@escaping HMRequestCallBack){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":appKey,
                      "client_secret":appSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":redirectUrl,
                      ]
      request(method: .POST, urlString: urlString, parameters: params, finished: finished)

    }
}


extension NetworkTools{
    func request(method:HMRequestMethod,urlString:String,parameters:[String:Any]?,finished:@escaping HMRequestCallBack){
        let sucess = { (_ task:URLSessionDataTask,_ result:Any?) -> Void in
            finished(result,nil)
        }
        //设置失败提示
        let failure = { (_ task:URLSessionDataTask?,_ error:Error?) ->Void in
            print(error ?? "")
            finished(nil,error)
        }
        if method == HMRequestMethod.GET {
            get(urlString, parameters: parameters, progress: nil, success:sucess , failure: failure)
        }else{
            post(urlString, parameters: parameters, progress: nil, success: sucess, failure: failure)
        }
    
    }
    
}
